﻿using System;
using System.IO;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using Appology.SugarSync.IO;
using Appology.SugarSync.IO.Primitives;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using System.Threading.Tasks;

namespace Appology.SugarSync.Explorer.Phone
{
    public partial class Browse : PhoneApplicationPage, ISuspend
    {
        public Browse()
        {
            InitializeComponent();
        }

        static Browse()
        {
            IsLaunch = true;
        }

        private static bool IsLaunch { get; set; }

        protected async override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (IsLaunch && PhoneApplicationService.Current.StartupMode != StartupMode.Activate)
            {
                if (string.IsNullOrEmpty(ApplicationState.Current.Username) ||
                    string.IsNullOrEmpty(ApplicationState.Current.Password))
                {
                    NavigationService.Navigate(new Uri("/Settings.xaml", UriKind.Relative));
                    return;
                }

                var applicationState = ApplicationState.Current;

                if (await applicationState.Account.AuthenticateAsync())
                {
                    await applicationState.Account.RefreshAsync();
                    await applicationState.StorageRoot.RefreshAsync();

                    DataContext = applicationState.StorageRoot;
                }
                else
                {
                    NavigationService.Navigate(new Uri("/Settings.xaml", UriKind.Relative));
                }

                IsLaunch = false;
            }
            else if(ApplicationState.Current.History.Count > 0)
            {
                SugarSyncPathInfo directoryInfo = ApplicationState.Current.History.Pop();
                DataContext = directoryInfo;
                directoryInfo.RefreshAsync();
            }
        }

        private void Settings_Click(object sender, EventArgs e)
        {
            ApplicationState.Current.History.Push((SugarSyncPathInfo)DataContext);
            NavigationService.Navigate(new Uri("/Settings.xaml", UriKind.Relative));
        }

        private void Refresh_Click(object sender, EventArgs e)
        {
            var directoryInfo = (SugarSyncDirectoryInfo) DataContext;
            directoryInfo.RefreshAsync();
        }

        private async void DeleteFolder_Click(object sender, EventArgs e)
        {
            var directoryInfo = (SugarSyncDirectoryInfo) DataContext;

            if (MessageBox.Show("Delete Directory and Contents?", "Are you sure?", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                await directoryInfo.Delete();

                await TaskEx.Delay(TimeSpan.FromSeconds(1));

                if (ApplicationState.Current.History.Count > 0)
                {
                    ContentPanel.Visibility = System.Windows.Visibility.Collapsed;
                    NavigationService.GoBack();
                }
                else
                {
                    MessageBox.Show("Folder Deleted.");
                }
            }
        }

        private void RenameFolder_Click(object sender, EventArgs e)
        {
            ApplicationState.Current.History.Push((SugarSyncPathInfo)DataContext);
            NavigationService.Navigate(new Uri("/RenameFolder.xaml", UriKind.Relative));
        }

        private void CreateFolder_Click(object sender, EventArgs e)
        {
            ApplicationState.Current.History.Push((SugarSyncPathInfo)DataContext);
            NavigationService.Navigate(new Uri("/CreateFolder.xaml", UriKind.Relative));
        }

        private async void Upload_Click(object sender, EventArgs e)
        {
            ApplicationState.Current.History.Push((SugarSyncDirectoryInfo) DataContext);

            var photoChooserTask = new PhotoChooserTask();

            photoChooserTask.Completed += async (s, args) =>
                                              {
                                                  var directoryInfo = (SugarSyncDirectoryInfo) ApplicationState.Current.History.Pop();

                                                  directoryInfo.IsBusy = true;

                                                  var fileInfo = await directoryInfo.CreateFileInfo(Path.GetFileName(args.OriginalFileName), "image/jpeg");
                                                  
                                                  using (var stream = await fileInfo.OpenWriteAsync())
                                                  {
                                                      args.ChosenPhoto.Copy(stream);
                                                  }

                                                  await TaskEx.Delay(TimeSpan.FromSeconds(1));

                                                  await directoryInfo.RefreshAsync();

                                                  directoryInfo.IsBusy = false;
                                              };

            photoChooserTask.ShowCamera = true;

            photoChooserTask.Show();
        }

        private async void Image_Loaded(object sender, RoutedEventArgs e)
        {
            var image = (Image) sender;

            var pathInfo = (SugarSyncPathInfo) image.DataContext;

            if (pathInfo is SugarSyncFileInfo)
            {
                var fileInfo = (SugarSyncFileInfo) pathInfo;

                await fileInfo.RefreshAsync();

                if (fileInfo.ContentType == "image/jpeg")
                {
                    try
                    {
                        var stream = await fileInfo.OpenPreviewImageAsync(75, 75, true, 0);

                        var bitmapImage = new BitmapImage();
                        bitmapImage.SetSource(stream);
                        image.Source = bitmapImage;
                    }
                    catch
                    {
                        var bitmapImage = new BitmapImage(new Uri("/Appology.SugarSync.Explorer.Phone;component/icons/Error.png", UriKind.Relative));
                        image.Source = bitmapImage;
                    }
                }
            }
        }

        public void Suspend()
        {
            ApplicationState.Current.History.Push((SugarSyncPathInfo)DataContext);
        }

        private void PathInfoButton_Click(object sender, RoutedEventArgs e)
        {
            var frameworkElement = (FrameworkElement)sender;

            if (frameworkElement.DataContext is SugarSyncDirectoryInfo)
            {
                var directoryInfo = (SugarSyncDirectoryInfo)frameworkElement.DataContext;
                
                ApplicationState.Current.History.Push((SugarSyncPathInfo)DataContext);

                ApplicationState.Current.History.Push(directoryInfo);

                // we add the id at the end of the uri to "trick" the navigation
                // framework into redirecting to this page...
                NavigationService.Navigate(new Uri(string.Format("/Browse.xaml?id={0}", Guid.NewGuid()), UriKind.Relative));
            }
            else if (frameworkElement.DataContext is SugarSyncFileInfo)
            {
                ApplicationState.Current.History.Push((SugarSyncPathInfo)DataContext);

                var fileInfo = (SugarSyncFileInfo)frameworkElement.DataContext;
                ApplicationState.Current.History.Push(fileInfo);

                NavigationService.Navigate(new Uri("/File.xaml", UriKind.Relative));
            }
        }
    }
}